<script setup>
import { ref, reactive } from 'vue'
import { listDept } from '@/api/system/dept'
import { Search } from '@element-plus/icons-vue'
const { proxy } = getCurrentInstance()
const props = defineProps({
  data: {
    type: Object,
    default: () => {}
  },

  // 是否禁用
  db: {
    type: Boolean,
    default: false
  }
})

// 封装 方法 字典查询
const {
  quality_standard // 质量标准
} = proxy.useDict('quality_standard')

const emit = defineEmits(['cancel', 'submit'])

const ruleFormRef = ref(null)

const selection = ref([])
const deptOptions = ref([])

const TableData = ref([])

const supplierIsShow = ref(false)
const materialShow = ref(false)

// 新增字段
const ruleForm = reactive({
  purchaseContractNo: '', //采购合同编号
  firstBatchTime: '', // 首批到货时间
  endBatchTime: '', // 末批到货时间
  estimatedTime: '', //到货时间
  remark: '', // 备注
  enclosureUrl: '', // 附件
  actualUnitPrice: '', // 实际单价
  actualWeight: '', // 实际数量
  supplierId: '', // 供应商id
  materialList: []
})

if (props.data?.id) {
  for (let key in props.data) {
    ruleForm[key] = props.data[key]
  }
}

const rules = reactive({
  purchaseContractNo: [{ required: true, message: '请填写采购合同编号', trigger: 'burl' }],
  firstBatchTime: [{ required: true, message: '请填写首批到货时间', trigger: 'change' }],
  endBatchTime: [{ required: true, message: '请填写末批到货时间', trigger: 'change' }],
  estimatedTime: [{ required: true, message: '请填写到货时间', trigger: 'change' }],
  enclosureUrl: [{ required: true, message: '请上传附件', trigger: 'change' }],
  supplierName: [{ required: true, message: '请填写供应商', trigger: 'change' }],
  demandDept: [{ required: true, message: '请选择需求部门', trigger: 'change' }],
  reviewComments: [{ required: true, message: '请填写评审意见', trigger: 'burl' }]
})

// 供应商选择
const preservation = val => {
  ruleForm.supplierName = val.supplierName
  ruleForm.supplierId = val.id
  supplierIsShow.value = false
}

/**
 * 物料信息弹窗
 */
const addTable = () => {
  materialShow.value = true
}

/**
 * 物料信息确认
 */
const materialSub = obj => {
  const arr = obj.list.map(item => ({
    materialId: item.materialId, // 物料id
    materialName: item.materialName, // 物料名称
    materialCode: item.materialCode, // 物料编码
    specType: item.specType, // 物料规格
    materialTypeName: item.materialTypeName, // 物料类别
    materialType: item.materialType, // 物料类别id
    actualUnitPrice: '',
    taxIncludedPrice: '',
    invoiceTaxRate: ''
  }))
  arr.forEach(items => {
    ruleForm.materialList.push(items)
  })
  materialShow.value = false
}

// 提交
const submit = () => {
  //   const startDate = new Date(ruleForm.firstBatchTime)
  //   const validitData = new Date(ruleForm.endBatchTime)
  //   const starttime = startDate.getTime() //起始时间戳
  //   const validittime = validitData.getTime() //结束时间戳

  return new Promise((resolve, reject) => {
    ruleFormRef.value.validate((valid, fields) => {
      if (!valid) {
        resolve(false)
        proxy.Mes('warning', '请填写完整')
        return
      }
      const isif = ruleForm.materialList.every(item => item.actualUnitPrice)
      if (!isif) {
        proxy.warningMsg('请填写实际单价！')
        resolve(false)
        return
      }
      //   if (Number(starttime) > Number(validittime)) {
      //     proxy.warningMsg('末批到货时间需要晚于首批到货时间！')
      //     resolve(false)
      //     return
      //   }

      // 赋值
      resolve(ruleForm)
    })
  })
}

// 列表选中
const handleSelectionChange = rows => {
  selection.value = rows
}

//输入实际单价时计算实际单价
const actualCalculate = record => {
  // 处理增值税税率为空或无效的情况，默认为 0
  const taxRate = Number(record.invoiceTaxRate) || 0
  // 如果增值税税率为 0，实际单价和含税单价应当相等
  if (taxRate === 0) {
    // 含税单价 = 实际单价
    record.taxIncludedPrice = Number(record.actualUnitPrice).toFixed(6)
  } else {
    // 含税单价 = 实际单价 + (实际单价 * 增值税税率)
    record.taxIncludedPrice = customFixed(
      Number(record.actualUnitPrice) + Number(record.actualUnitPrice) * (taxRate / 100),
      6
    )
  }
}

//输入含税单价时计算实际单价
const taxInclCalculate = record => {
  // 处理增值税税率为空或无效的情况，默认为 0
  const taxRate = Number(record.invoiceTaxRate) || 0
  // 如果增值税税率为 0，实际单价和含税单价应当相等
  if (taxRate === 0) {
    // 含税单价 = 实际单价
    record.actualUnitPrice = Number(record.taxIncludedPrice).toFixed(6)
  } else {
    // 含税单价/(增值税率/100+1)
    record.actualUnitPrice = customFixed(Number(record.taxIncludedPrice) / (1 + taxRate / 100), 6)
    //   (
    //   Number(record.taxIncludedPrice) -
    //   Number(record.taxIncludedPrice) * (taxRate / 100)
    // ).toFixed(6)
  }
}

/**
 * 计算-单价输入
 */
const calculate = record => {
  // 处理增值税税率为空或无效的情况，默认为 0
  const taxRate = Number(record.invoiceTaxRate) || 0

  // 如果增值税税率为 0，实际单价和含税单价应当相等
  if (taxRate === 0) {
    // 含税单价 = 实际单价
    record.taxIncludedPrice = Number(record.actualUnitPrice).toFixed(6)
  } else {
    // 含税单价 = 实际单价 + (实际单价 * 增值税税率)
    record.taxIncludedPrice = customFixed(
      Number(record.actualUnitPrice) + Number(record.actualUnitPrice) * (taxRate / 100),
      6
    )
  }
}

/**
 * 不进行四舍五入且保留小数
 * @param value
 * @param decimalPlaces
 */
function customFixed(value, decimalPlaces) {
  const factor = Math.pow(10, decimalPlaces)
  return Math.floor(value * factor) / factor
}

/**
 * 删除
 */
const remove = () => {
  if (selection.value.length > 0) {
    selection.value.forEach(item => {
      const Find = ruleForm.materialList.findIndex(itemy => item.materialId == itemy.materialId)
      ruleForm.materialList.splice(Find, 1)
    })
  } else {
    ruleForm.materialList.splice(ruleForm.materialList.length - 1, 1)
  }
}

function handleAdd(row) {
  listDept().then(response => {
    deptOptions.value = proxy.handleTree(response.data, 'deptId')
  })
  if (row != undefined) {
    ruleForm.demandDept = row.deptId
  }
}
handleAdd()
defineExpose({ submit })
</script>

<template>
  <div class="app-container">
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      label-position="right"
      inline
      scroll-to-error
      label-width="120px"
    >
      <el-form-item label="供应商信息" prop="supplierName">
        <el-input clearable :disabled="props.db" @click="supplierIsShow = true" v-model="ruleForm.supplierName" />
      </el-form-item>
      <el-form-item label="采购合同号">
        <el-input clearable :disabled="props.db" v-model="ruleForm.purchaseContractNo" />
      </el-form-item>
      <el-form-item label="预计到货时间" prop="estimatedTime">
        <el-date-picker
          v-model="ruleForm.estimatedTime"
          :disabled="props.db"
          type="datetime"
          placeholder="请选择预计到货时间"
          format="YYYY/MM/DD hh:mm:ss"
          value-format="YYYY-MM-DD hh:mm:ss"
        />
      </el-form-item>
      <div class="rk">
        <el-form-item label="备注" prop="remark">
          <el-input
            clearable
            :disabled="props.db"
            v-model="ruleForm.remark"
            :rows="3"
            type="textarea"
            placeholder="请输入备注"
            :input-style="{ width: '100%' }"
          />
        </el-form-item>
      </div>
      <div>
        <el-form-item label="上传附件">
          <FileUpload v-model="ruleForm.enclosureUrl" v-if="!props.db" />
          <DownloadFile :fileList="ruleForm.enclosureUrl" v-else />
        </el-form-item>
      </div>
    </el-form>
    <!-- 表格数据 -->
    <p-table-add title="明细项" @add="addTable" @remove="remove" />
    <el-table
      v-loading="loading"
      stripe
      border
      :data="ruleForm.materialList"
      style="margin-top: 10px"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" fixed="left" />
      <el-table-column label="序号" width="70" type="index" />
      <el-table-column label="物料编码" prop="materialCode" width="auto" />
      <el-table-column label="物料名称" prop="materialName" width="auto" />
      <el-table-column label="物料类别" prop="materialTypeName" width="auto" />
      <el-table-column label="规格型号" prop="specType" width="auto" />
      <el-table-column label="实际量" width="auto">
        <template #default="scope">
          <el-input type="number" oninput="if(value<=0)value=''" v-model="scope.row.actualWeight" clearable></el-input>
        </template>
      </el-table-column>
      <el-table-column label="实际单价" width="auto">
        <template #default="scope">
          <el-input
            type="number"
            v-model="scope.row.actualUnitPrice"
            clearable
            @change="actualCalculate(scope.row)"
          ></el-input>
        </template>
      </el-table-column>

      <el-table-column label="含税单价" width="auto">
        <template #default="scope">
          <el-input
            type="number"
            oninput="if(value<=0)value=''"
            v-model="scope.row.taxIncludedPrice"
            clearable
            @change="taxInclCalculate(scope.row)"
          ></el-input>
        </template>
      </el-table-column>

      <el-table-column label="增值税税率" width="auto">
        <template #default="scope">
          <el-input
            type="number"
            oninput="if(value<=0)value=''"
            v-model="scope.row.invoiceTaxRate"
            clearable
            @change="calculate(scope.row)"
          ></el-input>
        </template>
      </el-table-column>
    </el-table>
    <Supplier :is-show="supplierIsShow" @preservation="preservation" @cancel="supplierIsShow = false" />

    <Material
      :is-show="materialShow"
      :dict="[
        {
          label: '原料',
          value: '1'
        },
        {
          label: '半成品',
          value: '3'
        },
        {
          label: '辅料',
          value: '2'
        },
        {
          label: '成品',
          value: '4'
        }
      ]"
      :bdb="false"
      @preservation="materialSub"
      @cancel="materialShow = false"
    />
  </div>
</template>

<style lang="scss" scoped>
.btn {
  margin-top: 20px;
}

.rk ::v-deep .el-form-item {
  width: 100% !important;
}
</style>
